import React, { useState, useEffect } from 'react';
import { connect } from 'dva';
import {
  Tree,
  Icon,
  Skeleton,
  Modal,
  message,
  Empty,
  Tag,
  Button,
  Input,
  Form,
  Row,
  Col, Select,
} from 'antd';
import debounce from 'lodash/debounce';
import cloneDeep from 'lodash/cloneDeep';
import { useAntdTable, useBoolean } from '@umijs/hooks';
import ScrollBar from '@/components/ScrollBar';
import SlickTable from '@/components/SlickTable';
import request from '@/utils/request';
import AddRowModal from './AddRowModal';
import styles from '../index.less';
import Ikon from '@/components/Ikon';
import classNames from "classnames";

const { CheckableTag } = Tag;
const { TreeNode } = Tree;

function SetCondition({ size, visiable, close, status, data, callback, result, form }) {
  const [selectedRows, setSelectedRows] = useState([]);
  const { getFieldDecorator } = form;
  // 组织树数据
  const [TreeData, setTreeData] = useState([]);
  // 选中点击的值
  const [selectedKeysArr, setSelectedKeysArr] = useState(['']);
  // 初始化加载组织树loading
  const [loading, setLoading] = useState(false);

  // 属性规格列表级联属性值列表
  const [attrId, setAttrId] = useState('');
  const [rowSelectItem, setRowSelectItem] = useState();

  const [dataSource, setDataSource] = useState([]);
  const [tagList, setTagList] = useState([]);
  // 通用对象多选
  const [selectedTags, setSelectedTags] = useState([]);
  // 通用对象手输入
  const [inputList, setInputList] = useState([]);

  const { state, setTrue, setFalse } = useBoolean(false);
  // 展示为 通用对象类型：general 还是 个性对象类型 individ
  const [curType, setCurType] = useState('general');
  // 通用对象 划分 枚举类型 meju 与 手输类型 input
  const [generalType, setGeneralType] = useState('meju');
  // 个性对象表格数据
  const [tableDataSource, setTableDataSource] = useState([]);

  const handleSelectRows = selectedRows => {
    const individArr = [];
    const oldMejuArr = [];
    const oldInputArr = [];
    tagList.forEach((data1,index) => {
      if(data1[0] === 'individ'){
        individArr.push(data1);
      }else if(data1[0] === 'meju'){
        oldMejuArr.push(data1);
      }else if(data1[0] === 'input'){
        oldInputArr.push(data1);
      }
    });
    const tagArr = [];
    selectedRows.map(rowSelectItem => {
      // alert(JSON.stringify(rowSelectItem));
      setRowSelectItem(rowSelectItem);
      if(rowSelectItem.attrValueType === '2000'){
         const selectArr = [];
         selectArr[0] = "meju";
         let isOld = false;
          oldMejuArr.map(oldMejuItemArr => {
            oldMejuItemArr.map(oldMejuItem => {
              if(oldMejuItem.attr !== undefined && rowSelectItem.attrId === oldMejuItem.attr.attrId){
                selectArr.push(oldMejuItem);
                isOld = true;
              }
            })
          })
         if(isOld === false){
           rowSelectItem.attrValueList.map(selectItem => {
             selectArr.push({
               attr: {
                 attrCode: rowSelectItem.attrNbr,
                 attrId: rowSelectItem.attrId,
                 attrName: rowSelectItem.attrName,
                 objCode: JSON.parse(selectedKeysArr[0]).busiObjNbr,
                 objId: JSON.parse(selectedKeysArr[0]).busiObjId,
                 objName: JSON.parse(selectedKeysArr[0]).busiObjName,
               },
               attrValue: selectItem.attrValue,
               attrValueName: selectItem.attrValueName,
               leftBrackets: '',
               optType: '==',
               preLog: '&&',
               rightBrackets: '',
               isCheck: false,
             });
           });
         }
        tagArr.push(selectArr);
      }else{
        let isOld = false;
        oldInputArr.map(oldInputItemArr => {
          oldInputItemArr.map(oldInputItem => {
            if(oldInputItem.attr !== undefined && rowSelectItem.attrId === oldInputItem.attr.attrId){
              const inputArr = [];
              inputArr[0] = "input";
              inputArr.push(oldInputItem);
              tagArr.push(inputArr);
              isOld = true;
            }
          })
        })
        if(isOld === false){
          const inputArr = [];
          inputArr[0] = "input";
          inputArr.push({
            attr: {
              attrCode: rowSelectItem.attrNbr,
              attrId: rowSelectItem.attrId,
              attrName: rowSelectItem.attrName,
              objCode: JSON.parse(selectedKeysArr[0]).busiObjNbr,
              objId: JSON.parse(selectedKeysArr[0]).busiObjId,
              objName: JSON.parse(selectedKeysArr[0]).busiObjName,
            },
            attrValue: '',
            attrValueName: '',
            leftBrackets: '',
            optType: '==',
            preLog: '&&',
            rightBrackets: '',
          });
          tagArr.push(inputArr);
        }
      }
    });
    setTagList(tagArr.concat(individArr));
    setSelectedRows(selectedRows);
  };

  const handleClose = tag  => {
    const newRuleCondList = [];
    tagList.forEach((data1,index) => {
      const newData = [];
      data1.map(item => {
        if(tag.attrValue !== item.attrValue){
          newData.push(item);
        }
      });
      if(newData.length > 1){
        newRuleCondList.push(newData);
      }
    });
    // alert(JSON.stringify(newRuleCondList));
    setTagList(newRuleCondList);
  };

  const handleChange = (tag, checked) => {
    const newRuleCondList = [];
    tagList.forEach((data1,index) => {
      const newData = [];
      data1.map(item => {
        if(item.attr !== undefined && tag.attr.attrId === item.attr.attrId
            && tag.attrValue === item.attrValue){
          const item2 = cloneDeep(item);
          item2.isCheck = checked;
          newData.push(item2);
        }else{
          newData.push(item);
        }
      });
      if(newData.length > 1){
        newRuleCondList.push(newData);
      }
    });
    // alert(JSON.stringify(newRuleCondList));
    setTagList(newRuleCondList);
  };

  const handleSelectChange = (tag, value) => {
    const newRuleCondList = [];
    tagList.forEach((data1,index) => {
      const newData = [];
      data1.map(item => {
        if(item.attr !== undefined && tag.attr.attrId === item.attr.attrId
          && tag.attrValue === item.attrValue){
          const item2 = cloneDeep(item);
          item2.optType = value;
          newData.push(item2);
        }else{
          newData.push(item);
        }
      });
      if(newData.length > 1){
        newRuleCondList.push(newData);
      }
    });
    // alert(JSON.stringify(newRuleCondList));
    setTagList(newRuleCondList);
  };

  const handleInputChange = (tag, value) => {
    const newRuleCondList = [];
    tagList.forEach((data1,index) => {
      const newData = [];
      data1.map(item => {
        if(item.attr !== undefined && tag.attr.attrId === item.attr.attrId
          && tag.attrValue === item.attrValue){
          const item2 = cloneDeep(item);
          item2.attrValue = value;
          newData.push(item2);
        }else{
          newData.push(item);
        }
      });
      if(newData.length > 1){
        newRuleCondList.push(newData);
      }
    });
    // alert(JSON.stringify(newRuleCondList));
    setTagList(newRuleCondList);
  };

  const handleIndividChange = (tableData) => {
    const tagArr = [];
    tagList.forEach((data1,index) => {
      if(data1[0] !== 'individ'){
        tagArr.push(data1);
      }
    });
    if(tableData.length > 0){
      tableData.map(item => {
        const tableArr = [];
        tableArr[0]='individ';
        tableArr.push({
          attr: {
            attrCode: item.attrCode,
            attrId: '',
            attrName: '',
            objCode: '',
            objId: -2,
            objName: '个性化对象',
          },
          attrValue: item.attrValue,
          attrValueName: '',
          leftBrackets: '',
          optType: item.optType,
          preLog: '&&',
          rightBrackets: '',
        });
        tagArr.push(tableArr);
      });
    }
    // alert(JSON.stringify(tagArr));
    setTagList(tagArr);
  };

  const backSelectRows = selectedRows => {
    // alert(JSON.stringify(selectedRows));
    const arr = [];
    data.ruleCondList.map(item => {
      item.map(item1 => {
        arr.push(item1);
      });
    });
    // 通用对象多选
    const oldSelectArr = arr.filter(item => item.attr.attrId && item.attrValueName);
    // alert(JSON.stringify(oldSelectArr));
    const tagArr = [];
    selectedRows.map(rowSelectItem => {
      // alert(JSON.stringify(rowSelectItem));
      if(rowSelectItem.attrValueType === '2000'){
        const selectArr = [];
        selectArr[0] = "meju";
        rowSelectItem.attrValueList.map(selectItem => {
          let isChecked = false;
          let optTypeOld = "==";
          oldSelectArr.map(oldSelectItem => {
            if(selectItem.attrId === oldSelectItem.attr.attrId){
              if(selectItem.attrValueName === oldSelectItem.attrValueName){
                isChecked = true;
                optTypeOld = oldSelectItem.optType;
              }
            }
          });
          selectArr.push({
            attr: {
              attrCode: rowSelectItem.attrNbr,
              attrId: rowSelectItem.attrId,
              attrName: rowSelectItem.attrName,
              objCode: selectedRows.busiObjNbr,
              objId: selectedRows.busiObjId,
              objName: selectedRows.busiObjName,
            },
            attrValue: selectItem.attrValue,
            attrValueName: selectItem.attrValueName,
            leftBrackets: '',
            optType: optTypeOld,
            preLog: '&&',
            rightBrackets: '',
            isCheck: isChecked,
          });
        });
        tagArr.push(selectArr);
      }
    });
    // 通用对象 input
    const oldInputArr = arr.filter(item => item.attr.attrId && !item.attrValueName);
    oldInputArr.map(oldInputItem => {
        const inputArr = [];
        inputArr[0] = "input";
        inputArr.push(oldInputItem);
        tagArr.push(inputArr);
        // const inputName =`curInputValue${oldInputItem.attr.attrId}`;
        // form.setFieldsValue({[(()=>inputName)()]: oldInputItem.attrValue});
    });


    // 个性化表格
    const gxhArr = arr.filter(item => !item.attr.attrId);
    const gxhTableArr = [];
    gxhArr.map(item => {
      gxhTableArr.push({
        attrCode: item.attr.attrCode,
        optType: item.optType,
        attrValue: item.attrValue,
      });
      const individArr = [];
      individArr[0] = "individ";
      individArr.push(item);
      tagArr.push(individArr);
    });
    setTableDataSource(gxhTableArr);
    // alert(JSON.stringify(tagArr));
    setTagList(tagArr);
  };

  const backCondition = treeData => {
    const selectedRowsKeyArr = [];
    data.ruleCondList.map(item => {
      item.map(item1 => {
        const selectedRowObj = {};
        selectedRowObj.attrId = item1.attr.attrId;
        selectedRowsKeyArr.push(selectedRowObj);
      });
    });
    setSelectedRows(selectedRowsKeyArr);
    if(tagList.length <= 0 && selectedRowsKeyArr.length > 0){
      const selectDataArr = [];
      treeData.map(item => {
        item.busiObjAttrList.map(tableDataItem => {
          let isSelect = false;
          selectedRowsKeyArr.map(selItem =>{
            if(tableDataItem.attrId === selItem.attrId){
              isSelect = true;
            }
          });
          if(isSelect){
            tableDataItem.busiObjId=item.busiObjId;
            tableDataItem.busiObjNbr=item.busiObjNbr;
            tableDataItem.busiObjName=item.busiObjName;
            selectDataArr.push(tableDataItem);
          }
        });
      });
      backSelectRows(selectDataArr);
    }
  }

  // 初始化获取接口的Tree集合
  const queryTreeData = () => {
    setLoading(true);
    request('pmc/pms/RuleCfgController/showObjAttrTree', {
      data: {
        // 条件设置入参1200 结果设置为1300
        applyRuleObj: status === 'set' ? 0 : 1,
      },
    })
      .then(res => {
        if (res.success) {
          setTreeData(res.data);
          backCondition(res.data);
        } else {
          message.error(res.errMessage);
        }
      })
      .always(() => setLoading(false));
  };



  useEffect(() => {
      queryTreeData();
  }, []);

  // 遍历递归集合数据，渲染组织树
  const renderTreeNode = TreeArr => {
    if (TreeArr.length > 0) {
      return TreeArr.map(item => {
        return (
          <TreeNode
            icon={({ expanded }) => (
              /* eslint-disable */
              <Icon
                type={
                  expanded
                    ? item.children && item.children.length > 0
                      ? 'folder-open'
                      : 'file'
                    : item.children && item.children.length > 0
                    ? 'folder'
                    : 'file'
                }
              />
              /* eslint-enable */
            )}
            title={item.busiObjName}
            key={JSON.stringify(item)}
            isLeaf={item.children && item.children.length > 0 ? false : true}
            // 往组织树挂一个detaRef 可供外部获取选中的整个对象数据
            dataRef={item}
          >
            {item.children ? renderTreeNode(item.children) : null}
          </TreeNode>
        );
      });
    }
  };

  // 选中节点
  const selectTreeNode = selectedKeys => {
    /* eslint-disable */
    selectedKeys.length > 0
      ? (setSelectedKeysArr(selectedKeys),
        setDataSource(JSON.parse(selectedKeys[0]).busiObjAttrList))
      : (setSelectedKeysArr(selectedKeysArr),
        setDataSource(JSON.parse(selectedKeysArr[0]).busiObjAttrList));
    let obj = {};
    if (selectedKeys.length) {
      obj = JSON.parse(selectedKeys[0]);
    } else {
      obj = JSON.parse(selectedKeysArr[0]);
    }
    setCurType(obj.busiObjId === -2 ? 'individ' : 'general');
    // setAttrId('');
    // setRowSelectItem();
  };


  // 属性规格
  const rowSelect = record => {
    setRowSelectItem(record);
    setAttrId(record.attrId);
    if (record.attrValueType === '2000') {
      const list = cloneDeep(record.attrValueList);
      setTagList(list.length ? list : []);
      setGeneralType('meju');
    } else {
      setTagList([]);
      setGeneralType('input');

      const arr11 = inputList.filter(item => {
        if (item.attr.attrId === record.attrId) {
          return true;
        }
      });
      if (arr11.length) {
        setTimeout(() => {
          form.setFieldsValue({ curInputValue: arr11[0].attrValue });
        }, 10);
      } else {
        form.setFieldsValue({ curInputValue: '' });
      }
    }
  };
  const setRowClassName = record => {
    return record.attrId === attrId ? `${styles.clickRowStyle}` : '';
  };



  // 手输入的

  // 个性化对象的表格新增

  const callBack = value => {
    const data = cloneDeep(tableDataSource);

    data.push({
      ...value,
      /* eslint-disable */
      tableId:
        Math.max.apply(
          Math,
          tableDataSource.map(function(o) {
            return o.tableId;
          })
        ) === -Infinity
          ? 0
          : Math.max.apply(
              Math,
              tableDataSource.map(function(o) {
                return o.tableId;
              })
            ) + 1,
      /* eslint-enable */
    });
    setTableDataSource(data);
    handleIndividChange(data);
  };



  return (
    <Modal
      title={status === 'set' ? '条件设置' : '结果设置'}
      width="800px"
      destroyOnClose
      visible={visiable}
      okText="保存"
      onOk={() => {
        // console.log(selectedTags, tableDataSource);
        const resArr = [];
        let isEmpty = false;
        tagList.map(item => {
          const resType = item[0];
          if(resType === "meju"){
            let mejuIsEmpty = true;
            item.map(mejuItem =>{
              if(mejuItem !== "meju" && mejuItem.isCheck){
                resArr.push(mejuItem);
                mejuIsEmpty = false;
              }
            });
            if(mejuIsEmpty){
              // message.warn("已选条件，枚举型条件未选择，请确认");
              isEmpty = true;
            }
          }else if(resType === "input"){
            if(item[1].attrValue === '' || item[1].attrValue === null){
              // message.warn("已选条件，输入型条件为空，请确认");
              isEmpty = true;
            }
            resArr.push(item[1]);
          }else{
            resArr.push(item[1]);
          }
        });
        if(!isEmpty){
          callback(resArr);
          close();
        }else{
          message.warn("已选条件，有条件为空，请确认");
        }
      }}
      onCancel={close}
    >
      <Skeleton active loading={loading}>
        {TreeData.length > 0 ? (
          <div className={styles.scroll_main}>
            <div className={styles.scroll_left}>
              <ScrollBar autoHide autoHeight autoHeightMax={size.height * 0.4}>
                <div style={{ height: size.height * 0.7, paddingRight: '8px' }}>
                  <Tree
                    showIcon
                    onSelect={selectTreeNode}
                    selectedKeys={selectedKeysArr}
                    defaultExpandAll
                  >
                    {renderTreeNode(TreeData)}
                  </Tree>
                </div>
              </ScrollBar>
            </div>
            <div
              className={styles.scroll_content}
              style={{ paddingLeft: '16px', borderLeft: '1px solid #e8e8e8' }}
            >
              <ScrollBar autoHide autoHeight autoHeightMax={size.height * 0.4}>
                <div style={{ height: size.height * 0.7 }} className={classNames(styles.set_conditionright,styles.config_gg)}>
                  {/* eslint-disable */
                  dataSource.length || curType === 'individ' ? (
                    <>
                      {curType === 'general' ? (
                        <>
                          <div className="ant-detail-title">属性规格</div>
                          <SlickTable
                            rowKey={record => record.attrId}
                            selectedRowKeys={selectedRows.map(row => row.attrId)}
                            columns={[
                              {
                                title: '属性规格编码',
                                dataIndex: 'attrNbr',
                                ellipsis: true,
                                // render: (text, record) => {
                                //   const arr = selectedTags
                                //     .concat(inputList)
                                //     .filter(item => item.attr.attrId === record.attrId);
                                //   if (arr.length) {
                                //     return <span className="text-info">{text}</span>;
                                //   } else {
                                //     return text;
                                //   }
                                // },
                              },
                              {
                                title: '属性规格名称',
                                dataIndex: 'attrName',
                                ellipsis: true,
                              },
                              {
                                title: '属性类型',
                                dataIndex: 'attrValueType',
                                ellipsis: true,
                                render: text => {
                                  return text === '2000'
                                    ? '枚举类型'
                                    : text === '1000'
                                    ? '输入型'
                                    : text === '3000'
                                    ? '只读型'
                                    : '查询型';
                                },
                              },
                            ]}
                            pagination={false}
                            dataSource={dataSource}
                            pick="checkbox"
                            onSelectRow={handleSelectRows}
                            selectedRows={selectedRows}
                          />
                        </>
                      ) : (
                        <>
                          <div className="ant-detail-title">
                            <span>属性设置</span>
                            <span className="pull-right">
                              <Button type="primary" onClick={setTrue}>
                                添加
                              </Button>
                            </span>
                          </div>
                          <SlickTable
                            style={{ marginTop: 8 }}
                            rowKey={record => record.tableId}
                            pagination={false}
                            dataSource={tableDataSource}
                            columns={[
                              {
                                title: '左表达式',
                                dataIndex: 'attrCode',
                                ellipsis: true,
                              },
                              {
                                title: '操作符',
                                dataIndex: 'optType',
                                ellipsis: true,
                              },
                              {
                                title: '右表达式',
                                dataIndex: 'attrValue',
                                ellipsis: true,
                              },
                              {
                                title: '操作',
                                align: 'center',
                                width: 100,
                                render: (text, record) => {
                                  return (
                                    <span>
                                      <a
                                        onClick={() => {
                                          const arr = cloneDeep(tableDataSource);
                                          arr.map((item, index) => {
                                            if (item.tableId === record.tableId) {
                                              arr.splice(index, 1);
                                            }
                                          });
                                          setTableDataSource(arr);
                                          handleIndividChange(arr);
                                        }}
                                      >
                                        删除
                                      </a>
                                    </span>
                                  );
                                },
                              },
                            ]}
                          />
                        </>
                      )
                    }
                    </>
                  ): (
                    <Ikon status="404" subTitle="抱歉，暂无属性规格、属性值展示 ~" />
                  )
                  /* eslint-enable */
                  }
                </div>
              </ScrollBar>
            </div>
          </div>
        ) : (
          <Empty description="条件设置暂无数据节点" image={Empty.PRESENTED_IMAGE_SIMPLE} />
        )}
      </Skeleton>
      <div className="ant-detail-title" style={{ marginTop: 8 }}>
        已选条件
      </div>
      <ScrollBar autoHide autoHeight autoHeightMax={size.height * 0.3}>
        <div>
          {tagList && tagList.length > 0 ? (
            tagList.map((tag) => (
              <>
                <div style={{ paddingTop: '5px' }}>
                  <div className={styles.rule_title} style={{display:'inline-block',paddingRight:'8px'}}>
                    {tag[1].attr.attrId ? tag[1].attr.attrName : tag[1].attr.attrCode}
                  </div>
                  <div style={{display:'inline-block'}}>
                    <Select
                      defaultValue={tag[1].optType}
                      style={{ width: 100 ,paddingRight:'8px'}}
                      placeholder="请选择"
                      allowClear
                      disabled={tag[0] === 'individ' ? (true) : (false)}
                      onChange={value => {
                        handleSelectChange(tag[1],value);
                      }}
                    >
                      {result.map(item => {
                        return (
                          <Option key={item.attrValue} value={item.attrValue}>
                            {item.attrValueName}
                          </Option>
                        );
                      })}
                    </Select>
                  </div>
                  {tag[0] === 'meju' ? (
                    <div style={{display:'inline-block'}}>
                                            <span className={styles.radio}>
                                                {tag.map(i => (
                                                  i === 'meju'?'':
                                                    <CheckableTag
                                                      key={i.attrValue}
                                                      checked={i.isCheck}
                                                      onChange={checked => {
                                                        handleChange(i, checked);
                                                      }}
                                                    >
                                                      {i.attrValueName ? i.attrValueName : i.attrValue}
                                                    </CheckableTag>
                                                ))}
                                            </span>
                    </div>
                  ) : tag[0] === 'input' ? (
                    <div style={{display:'inline-block'}}>
                      {getFieldDecorator('curInputValue'+tag[1].attr.attrId,{
                        initialValue:tag[1].attrValue
                      })(
                        <Input
                          placeholder="请自定义输入属性值"
                          onChange={debounce(() => {
                            const value = form.getFieldValue('curInputValue'+tag[1].attr.attrId);
                            handleInputChange(tag[1],value);
                          }, 300)}
                        />
                      )}
                    </div>
                  ) : (
                    <div style={{display:'inline-block'}}>
                      <Input
                        defaultValue={tag[1].attrValue}
                        disabled={true}
                      />
                    </div>
                  )}
                </div>
              </>
            ))
          ) : (
            <Empty image={Empty.PRESENTED_IMAGE_SIMPLE}/>
          )}
        </div>
      </ScrollBar>
      {state ? (
        <AddRowModal
          visiable={state}
          close={setFalse}
          callback={callBack}
          result={result}
          status={status}
        />
      ) : null}
    </Modal>
  );
}

export default connect(({ setting }) => ({
  size: setting.size,
}))(Form.create()(SetCondition));
